package com.hspedu.newData.dmsxl.树.二叉树的遍历.层序遍历迭代法.队列;

import com.hspedu.newData.dmsxl.ds.TreeNode;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-21 
 * @Version: 1.0
 */

public class LC2583二叉树中的第k大层和 {

    public long kthLargestLevelSum(TreeNode root, int k) {

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        PriorityQueue<Long> queue1 = new PriorityQueue<>(new Comparator<Long>() {
            @Override
            public int compare(Long o1, Long o2) {
                return (int)(o1 - o2);
            }
        });

        while (!queue.isEmpty()){
            int len = queue.size();
            long sum = 0;
            while (len>0){

                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
                len--;
            }
            queue1.offer(sum);
            if (queue1.size() > k){
                queue1.poll();
            }
        }
        if (queue1.size() == k){
            return queue1.peek();
        }

        return -1l;
    }
}
